package com.project.smms.controller;

import com.project.smms.pojo.User;
import com.project.smms.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Collection;


/**
 * @author 莫息涛
 * @Description: 用户的控制器
 * @date 2020/3/5 19:44
 */
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/selectUser")
    public String selectUser(Model model){
        Collection<User> users = userService.selectUser();
        model.addAttribute("users",users);
        return "user";
    }

    @RequestMapping("/deleteUser/{user_id}")
    public String deleteUser(@PathVariable("user_id") Integer id,Model model){
        try {
            userService.deleteUser(id);
        }catch (Exception e){
            return "errordata";
        }finally {
            Collection<User> users = userService.selectUser();
            model.addAttribute("users",users);
        }
        return "user";
    }

    @RequestMapping("/toAddPage")
    public String toAddPage(){
        return "adduser";
    }


    @RequestMapping("/addUser")
    public String addUser(User user, Model model){
        try {
            userService.addUser(user);
        }catch (Exception e){
            return "errordata";
        }finally {
            Collection<User> users = userService.selectUser();
            model.addAttribute("users",users);
        }
        return "user";
    }

    @RequestMapping("/toUpdatePage/{user_id}")
    public String toUpdatePage(@PathVariable("user_id") Integer id,Model model){
        User user = userService.selectUserById(id);
        model.addAttribute("updateuser",user);
        return "updateuser";
    }

    @RequestMapping("/updateUser")
    public String updateUser(User user,Model model){
        try {
            userService.updateUser(user);
        }catch (Exception e){
            return "errordata";
        }finally {
            Collection<User> users = userService.selectUser();
            model.addAttribute("users",users);
        }
        return "user";
    }
}